﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThaiHoa.Win.QLSX.Entity;
using ThaiHoa.Win.QLSX.Kho.UTI;
using Excel = Microsoft.Office.Interop.Excel;
using ThaiHoa.Win.QLSX.DAL;

namespace ThaiHoa.Win.QLSX.Kho.UI
{
    public partial class frmCongNhanList : Form
    {
        #region Fields
        KhoDBContext db;

        BindingSource CongNhanBS;
        Access acs;
        frmCongNhanSearch _frmCongNhanSearch;

        #endregion
        #region Constructor
        public frmCongNhanList()
        {
            InitializeComponent();
        }
        #endregion
        #region Functions
        private void KhoiTao()
        {
            db = new KhoDBContext();
            db.Saved += new EventHandler(db_Saved);
            CongNhanBS = new BindingSource();
            acs = new Access();
            db.CongNhan.Include("LoaiCongNhan").Where(m => m.TrangThai).Load();
            CongNhanBS.DataSource = db.CongNhan.Local.ToBindingList();
            dgvCongNhan.DataSource = CongNhanBS;
            congNhanBN.BindingSource = CongNhanBS;
            CustomerGridView();
        }
        private void TimKiem(SearchEventArgs e)
        {
            db = new KhoDBContext();
            db.Saved += new EventHandler(db_Saved);
            CongNhanBS = new BindingSource();
            acs = new Access();
            db.CongNhan.Include("LoaiCongNhan")
                .Where(m => m.TrangThai
                    && m.HoVaTen.ToLower().Contains(e.Ten)
                    && m.LoaiCongNhan.Id.Equals(e.ChucVu.TenLoai.Equals("Tất Cả") ? m.LoaiCongNhan.Id : e.ChucVu.Id)
                    && m.NgaySinh.Value.Year.Equals(e.NamSinh.Equals(0) ? m.NgaySinh.Value.Year : e.NamSinh)
                    && m.DiaChi.ToLower().Contains(e.DiaChi)
                    && m.DienThoai.ToLower().Contains(e.DienThoai)
                    )
                .Load();
            CongNhanBS.DataSource = db.CongNhan.Local.ToBindingList();
            dgvCongNhan.DataSource = CongNhanBS;
            congNhanBN.BindingSource = CongNhanBS;
            CustomerGridView();
        }
        private void ReLoadData()
        {
            if (db != null) db.Dispose();
            KhoiTao();
        }

        private void CustomerGridView()
        {
            //Ẩn toàn bộ columns
            foreach (DataGridViewColumn item in dgvCongNhan.Columns)
            {
                item.Visible = false;
            }
            //Khóa tính năng thêm mới
            dgvCongNhan.AllowUserToAddRows = false;
            //Tùy chỉnh lại
            //Họ và tên
            var c = dgvCongNhan.Columns["HoVaTen"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 1;

            //Loại công nhân
            c = dgvCongNhan.Columns["LoaiCongNhan"];
            c.HeaderText = "Chức Vụ";
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 2;
            c.ReadOnly = true;

            //Giới tính
            List<Sex> sexList;
            sexList = new List<Sex>(new Sex[]{
               new Sex(true, "Nam"), 
               new Sex(false, "Nu")});

            DataGridViewComboBoxColumn gioiTinhColumn=new DataGridViewComboBoxColumn();
            gioiTinhColumn.DataSource=sexList;
            gioiTinhColumn.ValueMember="Type";
            gioiTinhColumn.DisplayMember="Name";
            gioiTinhColumn.DataPropertyName="GioiTinh";
            gioiTinhColumn.DisplayIndex=3;
            gioiTinhColumn.Width=100;
            gioiTinhColumn.HeaderText = "Giới Tính";
            dgvCongNhan.Columns.Add(gioiTinhColumn);

            //Ngày sinh
            c = dgvCongNhan.Columns["NgaySinh"];
            c.Visible = true;
            c.Width = 150;
            c.DisplayIndex = 4;
            c.DefaultCellStyle.Format = "dd/MM/yyyy";

            //Địa chỉ
            c = dgvCongNhan.Columns["DiaChi"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 5;

            //Điện thoại
            c = dgvCongNhan.Columns["DienThoai"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 6;

            //Ghi chú
            c = dgvCongNhan.Columns["GhiChu"];
            c.Visible = true;
            c.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            c.DisplayIndex = 7;

        }

        private void HienThiChiTiet()
        {
            CongNhan item = CongNhanBS.Current as CongNhan;
            if (item != null)
            {
                frmCongNhanDetail _frmCongNhanDetail = new frmCongNhanDetail();
                _frmCongNhanDetail.DBChanged += new EventHandler(_frmCongNhanDetail_DBChanged);
                acs.ShowFormCongNhanDetail(_frmCongNhanDetail, item.Id);
            }
        }

        private void Xoa()
        {
            CongNhan item = CongNhanBS.Current as CongNhan;
            if (Common.ShowMessengerConfirmDelete() == DialogResult.Yes)
            {
                if (item != null)
                {
                    db.CongNhan.Remove(item);
                    db.SaveChanges();
                }
            }
        }

        private void LuuLai()
        {
            if (Common.ShowMessengerConfirmSave() == DialogResult.Yes)
            {
                db.SaveChanges();
            }
        }
        private void ExportToExcel()
        {
            string workbookPath = Application.StartupPath + @"\Template\Excel\JAT_CongNhan";
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(workbookPath,
               0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[1];
            xlWorkBook.Activate();
            xlWorkSheet.Name = "CongNhan";
            //Add data
            var listCongNhan = CongNhanBS.List;
            int count = 0;
            int positonStart = 11;
            Excel.Range r;
            foreach (CongNhan item in listCongNhan)
            {
                xlWorkSheet.Cells[positonStart + count, 1] = count + 1;
                xlWorkSheet.Cells[positonStart + count, 2] = item.HoVaTen;
                xlWorkSheet.Cells[positonStart + count, 3] = item.LoaiCongNhan.TenLoai;
                xlWorkSheet.Cells[positonStart + count, 4] = item.GioiTinh ? "Nam" : "Nữ";
                xlWorkSheet.Cells[positonStart + count, 5] = item.NgaySinh.Value.ToString("dd/MM/yyyy");
                xlWorkSheet.Cells[positonStart + count, 6] = item.DiaChi;
                xlWorkSheet.Cells[positonStart + count, 7] = item.DienThoai;
                xlWorkSheet.Cells[positonStart + count, 8] = item.GhiChu;

                //Format it               

                string start = "A" + (count + positonStart).ToString();
                string stop = "J" + (count + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Borders.Color = Color.Black;
                r.RowHeight = 30;
                //r.Style.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                r.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                start = "H" + (count + positonStart).ToString();
                stop = "J" + (count + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Merge();
                count++;


            }
            xlWorkSheet.Cells[7, 9] = string.Format("Ngày {0}/{1}/{2}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year);
            // Hiện chương trình
            xlApp.Visible = true;

            //// Save file
            //xlWorkBook.SaveAs("C:\\JAT_VatTu_DanhMucThepDac_1.xls", Excel.XlFileFormat.xlWorkbookNormal,
            //                null, null, false, false,
            //                Excel.XlSaveAsAccessMode.xlExclusive,
            //                false, false, false, false, false);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
        }
        public void HienFormTimKiem()
        {
            _frmCongNhanSearch = new frmCongNhanSearch();
            _frmCongNhanSearch.Searched += new EventHandler<SearchEventArgs>(_frmCongNhanSearch_Searched);
            _frmCongNhanSearch.ShowDialog();
        }

        
        #endregion
        #region Events

        private void frmCongNhanList_Load(object sender, EventArgs e)
        {
            KhoiTao();
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            frmCongNhanDetail _frmCongNhanDetail = new frmCongNhanDetail();
            _frmCongNhanDetail.DBChanged += new EventHandler(_frmCongNhanDetail_DBChanged);
            acs.ShowFormCongNhanDetail(_frmCongNhanDetail, Guid.Empty);
        }



        private void btnInformation_Click(object sender, EventArgs e)
        {
            HienThiChiTiet();
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            ReLoadData();
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            Xoa();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvCongNhan_DoubleClick(object sender, EventArgs e)
        {
            HienThiChiTiet();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            LuuLai();
        }

        void db_Saved(object sender, EventArgs e)
        {
            ReLoadData();
        }
        void _frmCongNhanDetail_DBChanged(object sender, EventArgs e)
        {
            ReLoadData();
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportToExcel();
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            HienFormTimKiem();
        }
        void _frmCongNhanSearch_Searched(object sender, SearchEventArgs e)
        {
            TimKiem(e);
        }
        #endregion

        


    }
    class Sex
    {
        public bool Type { set; get; }

        public string Name { set; get; }

        public Sex(bool type, string name)
        {
            this.Type = type;

            this.Name = name;
        }
    }
}
